package front

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/response"
	"hft/global"
	maptool "hft/tools/map_tool"
	mapRes "hft/tools/map_tool/response"
)

type Site struct{}

func (*Site) GetAllSite(city int, ip string) (data *response.AllSiteRes, err error) {

	var list []*response.AllSite

	var siteRes response.AllSiteRes

	var res *mapRes.IpRes

	var defaultRegion *response.AllSite

	var myDefault *response.AllSite

	global.OC_DB.Model(&admin.Region{}).Where("is_default = ?", 1).First(&myDefault)

	if city == 0 {
		res, err = maptool.AmapApi.GetCityByIp(ip)

		if err != nil {
			return nil, errors.New("未知错误500")
		}

		if res.Status != "1" || res.InfoCode != "10000" {
			return nil, errors.New("未知错误500")
		}

		// 看看获得的城市是否为空
		if res.City == "" {
			siteRes.Site = *myDefault
		} else {
			err = global.OC_DB.Model(&admin.Region{}).Where("name = ?", res.City).First(&defaultRegion).Error

			if err != nil {
				return nil, errors.New("未知错误500")
			}
			siteRes.Site = *defaultRegion
		}

	} else {
		err = global.OC_DB.Model(&admin.Region{}).Where("id = ?", city).First(&defaultRegion).Error

		if err != nil {
			return nil, errors.New("未知错误500")
		}
	}

	global.OC_DB.Model(&admin.Region{}).Where("level = ?", "city").Select("id,name,first_word,is_hot,pre_fix,is_default,alias,longitude,latitude").Find(&list)
	for _, v := range list {
		v.Center = []float64{v.Longitude, v.Latitude}
	}
	siteRes.List = list

	return &siteRes, nil

}

var SiteService = new(Site)
